package chapter1.zyq1_str_obj;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** 服务端第二版： 服务端可以让多个客户端链接。 同时一次可以和多个客户端通信(发送文本字符串)(线程池实现)*/
public class Server3 {
    public static void main(String[] args) {
        Server3 server = new Server3();
        server.start();
    }

    //线程池，每个会话由一个线程处理
    private ExecutorService fixPool = Executors.newCachedThreadPool();
    public void start(){
        try {
            ServerSocket serverSocket = new ServerSocket(8002);
            System.out.println("服务器开启服务端口" + 8001 + ",等待连接请求...");
            while(true) {
                Socket socket = serverSocket.accept();
                System.out.println("接受客户端的连接，开始会话...");
                //设置服务端socket读超时为20000毫秒
                socket.setSoTimeout(1000);
                //把会话操作提交给线程池，由另外的线程单独处理会话。
                Thread t1=new Thread(){
                    public void run(){
                        try {
                            session(socket);
                            socket.close();
                            System.out.println("会话结束，服务端关闭连接。");
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                };
                fixPool.execute(t1);
                /*fixPool.execute(
                        ()->{
                            try {
                                session(socket);
                                socket.close();
                                System.out.println("会话结束，服务端关闭连接。");
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                );*/
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    protected void session(Socket socket) throws Exception {
        String msg = sendReceiveUtil_Str23.recvString(socket);
        System.out.println("Receive: " + msg);
        msg = "Fine, thank you!";
        sendReceiveUtil_Str23.sendString(socket, msg);
        System.out.println("Send: " + msg);
        msg = "And you?";
        sendReceiveUtil_Str23.sendString(socket, msg);
        System.out.println("Send: " + msg);
        msg = sendReceiveUtil_Str23.recvString(socket);
        System.out.println("Receive: " + msg);
    }

    //接收一个字符串


}
